package org.dromara.iot.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.domain.model.LoginUser;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.service.UserService;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.iot.domain.IotAnnualInspection;
import org.dromara.iot.domain.bo.IotAnnualInspectionBo;
import org.dromara.iot.domain.vo.IotAnnualInspectionVo;
import org.dromara.iot.domain.vo.IotAnnualPlanVo;
import org.dromara.iot.domain.vo.IotElevatorVo;
import org.dromara.iot.mapper.IotAnnualInspectionMapper;
import org.dromara.iot.service.IIotAnnualInspectionService;
import org.dromara.iot.service.IIotAnnualPlanService;
import org.dromara.iot.service.IIotElevatorService;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 电梯年检管理Service业务层处理
 *
 * @author lsl
 * @date 2024-06-16
 */
@RequiredArgsConstructor
@Service
public class IotAnnualInspectionServiceImpl implements IIotAnnualInspectionService {

    private final IotAnnualInspectionMapper baseMapper;

    private final IIotElevatorService elevatorService;

    private final IIotAnnualPlanService annualPlanService;

    private final UserService userService;
    /**
     * 查询电梯年检管理
     */
    @Override
    public IotAnnualInspectionVo queryById(Long inspectionId) {
        IotAnnualInspectionVo iotAnnualInspectionVo = baseMapper.selectVoById(inspectionId);
        IotAnnualPlanVo iotAnnualPlanVo = annualPlanService.queryById(iotAnnualInspectionVo.getPlanId());
        IotElevatorVo iotElevatorVo = elevatorService.queryById(iotAnnualPlanVo.getElevatorId());
        iotAnnualInspectionVo.setElevatorVo(iotElevatorVo);
        iotAnnualInspectionVo.setHeadManAvatar(userService.selectAvatarById(iotAnnualInspectionVo.getHeadUserId()));
        return iotAnnualInspectionVo;
    }

    /**
     * 查询电梯年检管理列表
     */
    @Override
    public TableDataInfo<IotAnnualInspectionVo> queryPageList(IotAnnualInspectionBo bo, PageQuery pageQuery) {
        QueryWrapper<IotAnnualInspection> query = Wrappers.query();
        query.like(StringUtils.isNotBlank(bo.getElevatorName()), "ie.elevator_name", bo.getElevatorName());
        query.eq(bo.getPlanId() != null, "ai.plan_id", bo.getPlanId());
        query.eq(StringUtils.isNotBlank(bo.getInspectionStatus()), "ai.inspection_status", bo.getInspectionStatus());
        Page<IotAnnualInspectionVo> result = baseMapper.selectOwnVoPage(pageQuery.build(), query);
        return TableDataInfo.build(result);
    }

    /**
     * 查询电梯年检管理列表
     */
    @Override
    public List<IotAnnualInspectionVo> queryList(IotAnnualInspectionBo bo) {
        LambdaQueryWrapper<IotAnnualInspection> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<IotAnnualInspection> buildQueryWrapper(IotAnnualInspectionBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<IotAnnualInspection> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getPlanId() != null, IotAnnualInspection::getPlanId, bo.getPlanId());
        lqw.like(StringUtils.isNotBlank(bo.getElevatorName()), IotAnnualInspection::getElevatorName, bo.getElevatorName());
        lqw.eq(bo.getAnnualDate() != null, IotAnnualInspection::getAnnualDate, bo.getAnnualDate());
        lqw.eq(StringUtils.isNotBlank(bo.getCheckSpeedLimiter()), IotAnnualInspection::getCheckSpeedLimiter, bo.getCheckSpeedLimiter());
        lqw.eq(StringUtils.isNotBlank(bo.getCheckThrough()), IotAnnualInspection::getCheckThrough, bo.getCheckThrough());
        lqw.eq(StringUtils.isNotBlank(bo.getInspectionStatus()), IotAnnualInspection::getInspectionStatus, bo.getInspectionStatus());
        lqw.eq(StringUtils.isNotBlank(bo.getHeadMan()), IotAnnualInspection::getHeadMan, bo.getHeadMan());
        lqw.eq(bo.getHeadUserId() != null, IotAnnualInspection::getHeadUserId, bo.getHeadUserId());
        lqw.eq(bo.getStartTime() != null, IotAnnualInspection::getStartTime, bo.getStartTime());
        lqw.eq(bo.getCompletionTime() != null, IotAnnualInspection::getCompletionTime, bo.getCompletionTime());
        lqw.eq(StringUtils.isNotBlank(bo.getInspectionContext()), IotAnnualInspection::getInspectionContext, bo.getInspectionContext());
        lqw.eq(StringUtils.isNotBlank(bo.getInspectionImg()), IotAnnualInspection::getInspectionImg, bo.getInspectionImg());
        return lqw;
    }

    /**
     * 新增电梯年检管理
     */
    @Override
    public Boolean insertByBo(IotAnnualInspectionBo bo) {
        IotAnnualPlanVo iotAnnualPlanVo = annualPlanService.queryById(bo.getPlanId());
        //添加年检时间
        bo.setAnnualDate(iotAnnualPlanVo.getAnnualDate());
        IotAnnualInspection add = MapstructUtils.convert(bo, IotAnnualInspection.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setInspectionId(add.getInspectionId());
        }
        return flag;
    }

    /**
     * 修改电梯年检管理
     */
    @Override
    public Boolean updateByBo(IotAnnualInspectionBo bo) {
        IotAnnualInspection update = MapstructUtils.convert(bo, IotAnnualInspection.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(IotAnnualInspection entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除电梯年检管理
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    /**
     * 开始年检
     *
     * @param inspectionId 年检ID
     * @return 结果
     */
    @Override
    public Boolean startAnnualInspection(Long inspectionId) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        IotAnnualInspectionVo annualInspectionVo = this.queryById(inspectionId);

        /**
         * 校验是否被接单
         */
        if (ObjectUtil.isNotNull(annualInspectionVo.getHeadUserId()) && !annualInspectionVo.getHeadUserId().equals(loginUser.getUserId())) {
            throw new ServiceException("该年检已归维保人员负责 ！");
        }
        //修改年检状态
        annualInspectionVo.setInspectionStatus("1");
        //添加负责人
        annualInspectionVo.setHeadMan(loginUser.getNickname());
        annualInspectionVo.setHeadUserId(loginUser.getUserId());
        //年检启动时间
        annualInspectionVo.setStartTime(new Date());
        baseMapper.updateById(BeanUtil.toBean(annualInspectionVo, IotAnnualInspection.class));
        return true;
    }

    /**
     * 确认年检
     *
     * @param bo 年检信息
     * @return 结果
     */
    @Override
    public Boolean confirmAnnualInspection(IotAnnualInspectionBo bo) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        IotAnnualInspectionVo iotAnnualInspectionVo = this.queryById(bo.getInspectionId());
        /**
         * 校验是否本人的单子
         */
        if (!iotAnnualInspectionVo.getHeadUserId().equals(loginUser.getUserId())) {
            throw new ServiceException("您不是该年检的负责人，无法完成 ！");
        }
        //修改年检状态
        bo.setInspectionStatus("2");
        //年检完成时间
        bo.setCompletionTime(new Date());
        this.updateByBo(bo);
        return true;
    }

}
